<script setup>
import { find, includes, map } from 'lodash-es';
import { useRequest, useWatch } from '@/hooks';
import { useSelectIns } from '@/store/zdwh.js';
import { getList, getEntInfo, deleteEnterprise } from '@/api/index.js';
import { Message, MessageBox } from 'element-ui';
import ToolTip from '@/components/ToolTip/index.vue';
import InsForm from './InsForm.vue';

const props = defineProps({
  isEdit: { type: Boolean, default: false },
  isDefaultSelect: { type: Boolean, default: () => false },
});
const emit = defineEmits(['checkedChange']);
const { proxy } = getCurrentInstance();
const selectInsStore = useSelectIns();
const visible = ref(false);
const filterText = ref('');
// const searchLoading = ref(false);
const searchList = ref([]);
const seRadio = ref('');
const submitNum = ref(0);
const dialogData = ref({
  open: false, //机构
  title: '',
});

const [enterpriseList, searchLoading, run] = useRequest(getList, {
  defaultParams: [{ enterpriseName: '' }],
  onSuccess: res => {
    selectInsStore.setSelectIns(res.data?.[0]);
  },
});
const [entInfo, , entRun] = useRequest(getEntInfo, {
  manual: true,
});
const [, , deleteRun] = useRequest(deleteEnterprise, {
  manual: true,
  onSuccess: res => {
    if (res.msg === '操作成功') {
      Message.success(res.msg);
      run({ enterpriseName: '' });
    } else {
      Message.error(res.msg);
    }
  },
});
const changeInput = () => {
  if (filterText.value.length > 0) {
    searchLoading.value = true;
    searchList.value = [];
    map(enterpriseList.value, v => {
      includes(v.enterpriseName, filterText.value) ? searchList.value.push(v) : null;
    });

    visible.value = true;
    searchLoading.value = false;
  } else {
    visible.value = false;
  }
};
const selectSearchItem = item => {
  if (item) {
    visible.value = false;
    seRadio.value = item;
    const entChecked = find(enterpriseList.value, v => v.enterpriseCode === seRadio.value);
    emit('checkedChange', entChecked);
  }
};
const handleFocus = () => {
  visible.value = filterText.value.length > 0 ? true : false;
};
const checkedChange = () => {
  const entChecked = find(enterpriseList.value, v => v.enterpriseCode === seRadio.value);
  emit('checkedChange', entChecked);
};
const currentStyles = (id, item) => {
  if (proxy.$store.state.global.setting.sideTheme === 'theme-light') {
    return id === item ? { backgroundColor: '#bfd7df' } : '';
  } else {
    return id === item ? { backgroundColor: 'rgba(0, 0, 0, 0.6)' } : '';
  }
};
const cancel = () => {
  dialogData.value.open = false;
};
const handleAdd = () => {
  dialogData.value.open = true;
  dialogData.value.title = '新增';
};
const handleEdit = item => {
  entRun({ enterpriseCode: item.enterpriseCode });
  dialogData.value.open = true;
  dialogData.value.title = '编辑';
};
const submitForm = () => {
  submitNum.value = submitNum.value + 1;
};
const handleSuccess = () => {
  cancel();
  run({});
};
const handleDelete = item => {
  MessageBox.confirm('删除后不可找回，是否确认删除', '提示', {
    confirmButtonText: '是',
    cancelButtonText: '否',
    type: 'warning',
  })
    .then(() => {
      deleteRun({ enterpriseCode: item.enterpriseCode });
    })
    .catch(() => {});
};
useWatch(enterpriseList, n => {
  if (n?.length > 0) {
    seRadio.value = props.isDefaultSelect ? n[0].enterpriseCode : null;
    checkedChange();
  }
});
</script>
<template>
  <div class="u-h100" v-loading="searchLoading">
    <div class="se-input">
      <el-popover placement="bottom" width="290" trigger="manual" v-model="visible" popper-class="u-base-fg">
        <ul
          v-show="filterText.length > 0 && searchList.length !== 0"
          class="su-searchBox"
          :class="$store.state.global.setting.sideTheme === 'theme-light' ? 'su-searchBox-light' : 'su-searchBox-dark'"
          v-loading="searchLoading"
        >
          <li v-for="item in searchList" :key="item.enterpriseCode" @click="selectSearchItem(item.enterpriseCode)">
            {{ item.enterpriseName }}
          </li>
        </ul>
        <div v-show="searchList.length === 0" style="text-align: center; min-height: 100px">无数据</div>
        <el-input
          suffix-icon="el-icon-search"
          size="small"
          slot="reference"
          placeholder="查询"
          @input="changeInput(filterText)"
          @blur="visible = false"
          @focus="handleFocus"
          v-model="filterText"
          clearable
        ></el-input>
      </el-popover>
    </div>
    <el-button
      v-if="isEdit"
      class="u-m20"
      icon="el-icon-plus"
      size="small"
      type="primary"
      plain
      style="width: calc(100% - 40px); margin-bottom: 0"
      @click="handleAdd"
    >
      新增机构
    </el-button>
    <div class="se-tyRadio" :style="{ height: isEdit ? 'calc(100% - 151px)' : 'calc(100% - 100px)' }">
      <el-radio-group
        v-if="enterpriseList?.length > 0"
        v-model="seRadio"
        @input="checkedChange"
        v-loading="searchLoading"
      >
        <el-radio
          v-for="(item, idx) in enterpriseList"
          :label="item.enterpriseCode"
          :key="item.enterpriseCode + '-' + idx"
          :style="currentStyles(seRadio, item.enterpriseCode)"
        >
          <div class="u-df-spb">
            <ToolTip :content="item.enterpriseName" effect="dark" />
            <div v-if="isEdit">
              <i class="el-icon-edit-outline u-mr5" @click="handleEdit(item)"></i>
              <i class="el-icon-delete" @click="handleDelete(item)"></i>
            </div>
          </div>
        </el-radio>
      </el-radio-group>
      <div v-else class="u-df-ct u-fs14 u-mt20 u-sec-text">暂无数据</div>
    </div>
    <el-dialog :visible.sync="dialogData.open" width="70%" :before-close="cancel" append-to-body>
      <div slot="title" class="dialog-title">
        <span class="tit">
          {{ dialogData.title }}-
          <span class="u-prim-text">机构</span>
        </span>
      </div>
      <InsForm
        :isEdit="true"
        :title="dialogData.title"
        :cancel="!dialogData.open"
        :submit="submitNum"
        @onSuccess="handleSuccess"
        :infoData="entInfo"
      />
      <div slot="footer" class="dialog-footer">
        <el-button size="small" @click="cancel" type="primary" plain>取 消</el-button>
        <el-button type="primary" size="small" @click="submitForm">保 存</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<style lang="scss" scoped>
.u-m20 {
  margin: 20px;
}
.se-input {
  padding: 20px 20px 0 20px;
}
// i {
//   transform: rotate(90deg);
// }

.se-tyRadio {
  margin: 20px;
  padding: 0;
  width: calc(100% - 40px);
  .el-radio-group {
    margin: 0;
    // padding: 20px;
  }
  // :deep(.el-radio__label) {
  //   font-size: 13px !important;
  // }
}
</style>
